﻿#include <iostream>
#include <vector>
using namespace std;


class Solution
{
public:
    // 1049. 最后一块石头的重量 II
    /*int lastStoneWeightII(vector<int>& stones)
    {
        int sum = 0;
        for (auto num : stones)
            sum += num;

        int V = sum / 2;
        int n = stones.size();

        vector<vector<int>> dp(n + 1, vector<int>(V + 1));
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= V; j++)
            {
                dp[i][j] = dp[i - 1][j];
                if (j >= stones[i - 1])
                    dp[i][j] = max(dp[i][j], dp[i - 1][j - stones[i - 1]] + stones[i - 1]);
            }

        return sum - 2 * dp[n][V];
    }*/

    // 优化
    int lastStoneWeightII(vector<int>& stones)
    {
        int sum = 0;
        for (auto num : stones)
            sum += num;

        int V = sum / 2;
        int n = stones.size();

        vector<int> dp(V + 1);
        for (int i = 1; i <= n; i++)
            for (int j = V; j >= 0; j--)
                if (j >= stones[i - 1])
                    dp[j] = max(dp[j], dp[j - stones[i - 1]] + stones[i - 1]);

        return sum - 2 * dp[V];
    }
};

int main()
{
    vector<int> v{ 2,7,4,1,8,1,7 };
    cout << Solution().lastStoneWeightII(v) << endl;

    return 0;
}